package models

import (
	"gorm.io/gorm"
)

type Wz struct {
	gorm.Model
	Title  string `gorm:"type:varchar(50); not null; commit:'标题'"`
	Name   string `gorm:"type:varchar(50); not null; commit:'栏目名称'"`
	TypeId int    `gorm:"type:int(50); not null; commit:'文章类别'"`
	Write  string `gorm:"type:varchar(50); not null; commit:'创建人'"`
	Like   string `gorm:"type:int(225); not null; commit:'浏览'"`
	Status string `gorm:"type:varchar(50); not null; commit:'状态'"`
}

func (w *Wz) Create() error {
	return DB.Create(&w).Error
}
func (w *Wz) Update() error {
	return DB.Updates(&w).Error
}
func (w *Wz) Del() error {
	return DB.Delete(&w).Error
}
func (w *Wz) List(keyword string, TypeId, page, pageSize int) (lists []*Wz, err error) {
	db := DB.Debug()
	if TypeId != 0 {
		db = db.Where("type_id=?", TypeId)
	}
	err = db.Where("title like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&lists).Error
	return
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
